package com.gxa.p2p.util;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/*
    文件上传工具类
        实现接收一个FormData（多个）中的数据
 */
public class FileUploadUtil {

    public static List<Map<String, Object>> upload(List<MultipartFile> multipartFileList, HttpServletRequest request) throws IOException {
        System.out.println(multipartFileList);
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < multipartFileList.size(); i++) {
            String originalFilename = multipartFileList.get(i).getOriginalFilename();
            System.out.println("originalFilename" + originalFilename);
            //从原始文件名中获得后缀,作为新添加文件的文件名后缀(匹配)
            String subfix = originalFilename.substring(originalFilename.indexOf(".") + 1);
            System.out.println("subfix:" + subfix);
            //使用UUID作为文件名,保证服务器中存放的文件名字唯一
            String targetFile = UUID.randomUUID().toString().replace("-", "") + i + "." + subfix;
            System.out.println(targetFile);

            //通过request获得当前程序的根路径
            String path = request.getServletContext().getRealPath("/");
            String fileName = path + "static/uploading/" + targetFile;
            System.out.println("Filename:" + fileName);
            //构建文件对象
            File uploadFile = new File(fileName);
            //核心操作:
            multipartFileList.get(i).transferTo(uploadFile);
            //返回0状态表示上传成功
            MapUtil mapUtil = new MapUtil();
            mapUtil.setCode(0);
            mapUtil.setMsg("添加成功！！！");
            mapUtil.put("fileName", targetFile);
            list.add(mapUtil.getMap());
        }
        return list;
    }
}
